var http = require('http');
var url = require('url');
var fs = require('fs');

var server = http.createServer();

var htmlDir = __dirname + '/html/';             // 父目录下的html文件夹

server.on('request', function (req, res) {
    var urlStr = url.parse(req.url);
    switch (urlStr.pathname) {
        case '/':
            sendData(htmlDir + 'index.html', req, res);
            break;

        case '/user':
            sendData(htmlDir + 'user.html', req, res);
            break;

        default:
            sendData(htmlDir + 'err.html', req, res);          //因为没有err.html，所以实际显示还是下面函数里的
            break;
    }
});

function sendData(file,req,res) {
    fs.readFile(file,function (err,data) {
        if(err){
            res.writeHead(404, {
                'content-type': 'text/html;charset=utf-8'
            });
            res.end('<p>地址不正确</p>')
        }else{
            res.writeHead(200, {
                'content-type': 'text/html;charset=utf-8'
            });
            res.end(data)
        }
    })
}

server.listen(9000, 'localhost');
